package cn.hfuu;

import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.conf.Configuration;

public class HBaseExample {
    public static void main(String[] args) {
        try {
            // 配置HBase
            Configuration config = HBaseConfiguration.create();
            config.set("hbase.zookeeper.quorum", "localhost"); // 设置Zookeeper服务器的地址
            config.set("hbase.zookeeper.property.clientPort", "2181");

            // 创建HBase连接
            Connection connection = ConnectionFactory.createConnection(config);
            Admin admin = connection.getAdmin();

            // 创建表名和列族
            String tableName = "my_table";
            String columnFamily = "cf";

            // 如果表已存在，则删除表
            if (admin.tableExists(TableName.valueOf(Bytes.toBytes(tableName)))) {
                System.out.println("Table exists, deleting...");
                admin.disableTable(TableName.valueOf(Bytes.toBytes(tableName)));
                admin.deleteTable(TableName.valueOf(Bytes.toBytes(tableName)));
            }

            // 创建表
            TableDescriptor tableDescriptor = TableDescriptorBuilder.newBuilder(TableName.valueOf(Bytes.toBytes(tableName)))
                    .setColumnFamily(ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes(columnFamily)).build())
                    .build();
            admin.createTable(tableDescriptor);
            System.out.println("Table created successfully.");

            // 获取表的操作句柄
            Table table = connection.getTable(TableName.valueOf(Bytes.toBytes(tableName)));

            // 插入数据
            for (int i = 1; i <= 4; i++) {
                Put put = new Put(Bytes.toBytes("row" + i)); // 每行的RowKey
                put.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes("col1"), Bytes.toBytes("value" + i));
                table.put(put);
                System.out.println("Inserted row" + i);
            }

            // 关闭连接
            table.close();
            admin.close();
            connection.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
